package com.woniuxy.reader.controller;


import com.woniuxy.reader.service.SubscribeService;
import com.woniuxy.result.Result;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.reader.entity.Chapter;
import com.woniuxy.reader.entity.Subscribe;
import com.woniuxy.reader.service.ChapterService;
import com.woniuxy.reader.service.SubscribeService;
import com.woniuxy.result.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zh_o
 * @since 2020-10-12
 */
@RestController
@RequestMapping("/subscribe")
public class SubscribeController {

    @Autowired
    private SubscribeService subscribeService;

    @Autowired
    private ChapterService chapterService;

    /**
     * 判断是否已订阅此章节
     * @param userId 用户id
     * @param chapterId 章节id
     * @return
     */
    @GetMapping("{userId}/{chapterId}")
    public boolean isSubscribed(@PathVariable("userId") Integer userId, @PathVariable("chapterId") Integer chapterId) {
        // 获取书籍信息
        Chapter chapterInfo = chapterService.getChapterInfo(chapterId);
        // 前十二章免费
        if (chapterId < (chapterInfo.getMinId() + 13)) {
            return true;
        }
        return subscribeService.getOne(new QueryWrapper<Subscribe>().eq(Subscribe.CHAPTER_ID, chapterId).eq(Subscribe.USER_ID, userId)) != null;
    }

    /**
     * 新增订阅
     * @param subscribe
     * @return
     */
    @PostMapping
    public Object insert(Subscribe subscribe){
        subscribeService.insertSubscribe(subscribe);
        return ResponseResult.success();
    }



    @GetMapping("{userId}")
    @ApiOperation("根据userID查询订阅")
    public Result selectSubscribeByUserId(@PathVariable("userId") String userId){
        System.out.println(userId);
        return Result.success(subscribeService.selectSubscribeByUserId(userId));
    }
}

